import 'package:base_plugin/base_plugin.dart';
import 'package:dio/dio.dart';
import 'package:finance_app/src/page/dashboard/expense/new_expense_page.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

mixin RefreshMixin<D, T extends List> on BaseProvider<D> {
  RefreshController refreshController = RefreshController();

  int get initPage => 1;

  int get initRows => 15;
  int page;
  int rows;
  bool hasUp = false;

  T get dataList;

  Future get refreshFuture;

  @override
  void initState() {
    page = initPage;
    rows = initRows;
    super.initState();
  }

  bool get canRefreshFuture => true;

  Future<void> onRefresh() async {
    page = initPage;
    if (canRefreshFuture) await onLoadRefreshData();
    refreshController.refreshCompleted();
  }

  Future<void> onLoadRefreshData() async {
    page = initPage;
    await post(refreshFuture, onSuccess: (result) {
      final data = getFromRequestResult(result, true);
      // if (data is List<TransactionEntity>)
      //   hasUp = false;
      // else
      hasUp = data.length >= rows;

      addData(data, true);
      update();
    }, autoHandler: AutoHandler.Toast);
  }

  void addData(T data, bool isRefresh) {
    T oldDataList = dataList;
    if (isRefresh) {
      oldDataList.clear();
    }
    oldDataList.addAll(data);
  }

  void onLoadMore() async {
    page++;
    await post(refreshFuture,
        onSuccess: (result) {
          final data = getFromRequestResult(result, false);
          // if (data is List<TransactionEntity>)
          //   hasUp = false;
          // else
          hasUp = data.length >= rows;
          addData(data, false);
          update();
        },
        autoHandler: AutoHandler.Toast,
        onError:
            (int statusCode, String msg, Object error, StackTrace stackTrace) {
          page--;
        });
    refreshController.loadComplete();
  }

  T getFromRequestResult(Response result, bool isRefresh);
}
